package example.demo.customerValidator.sequenceprovider;

import example.demo.bean.Employee;
import org.hibernate.validator.spi.group.DefaultGroupSequenceProvider;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/*
 * @GroupSequenceProvider(EmployeeGroupSequenceProvider.class)
 * public class Employee {......}//Employee要使用动态分组时，就要在类上那样做。
 *
 * 校验是先有组，再去参数校验
 */
public class EmployeeGroupSequenceProvider implements DefaultGroupSequenceProvider<Employee> {
    /**
     * 举例
     * 1、员工的 age 在 20-25 之间，title 必须以 "初级" 开头
     * 2、员工的 age 在 25-30 之间，title 必须以 "中级" 开头
     * 3、否则，不做验证
     */
    @Override
    public List<Class<?>> getValidationGroups(Employee employee) {
        List<Class<?>> defaultGroupSequence = new ArrayList<>();
        defaultGroupSequence.add(Employee.class);//  相当于添加了默认组 javax.validation.groups.Default，这段代码一定要加，不加就报错
        if (employee != null) {
            if (20 < employee.getAge() && employee.getAge() <= 25) {
                defaultGroupSequence.add(Employee.TitleJunior.class);
            } else if (25 < employee.getAge() && employee.getAge() <= 30) {
                defaultGroupSequence.add(Employee.TitleMiddle.class);
            }
        }
        return defaultGroupSequence;
    }



    public static void main(String[] args) {
        Class<EmployeeGroupSequenceProvider> providerClass = EmployeeGroupSequenceProvider.class;
        Type[] genericInterfaces = providerClass.getGenericInterfaces();
        Type genericSuperclass = providerClass.getGenericSuperclass();
        Type genericInterface = genericInterfaces[0];
        Class clazz = null;
        if (genericInterface instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) genericInterface;
            Type[] typeArguments = parameterizedType.getActualTypeArguments();
            Type typeArgument = typeArguments[0];
            if (typeArgument instanceof Class) {
                clazz = (Class) typeArgument;
            }else {
                String typeName = typeArgument.getTypeName();
                try {
                    clazz=Class.forName(typeName);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println();
    }
}
